use tokio_modbus::prelude::*;
use anyhow::Result;
use crate::config::ModbusSlave;

/*
    modbus 主站相关逻辑
    主站会轮询配置的从站，从从站中采取指定寄存器中的数据
*/

// 轮询从站，采集modbus信息
pub async fn poll_slave(slave: ModbusSlave) -> Result<()> {
    let addr = slave.addr.parse()?;
    let mut ctx = tcp::connect(addr).await?;
    log::info!("Connected to slave: {}", slave.name);

    let data = ctx.read_input_registers(slave.start_reg, slave.reg_count).await?;
    log::info!(
        "Slave [{}] registers ({}..{}): {:?}",
        slave.name,
        slave.start_reg,
        slave.start_reg + slave.reg_count,
        data
    );

    ctx.disconnect().await?;
    Ok(())

}